package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.config.MailConfig;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 注册接口实现
 * created by feng on 7/21/21
 */

@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private MailConfig mailConfig;

    @Override
    public UserRegisterResponse register(UserRegisterRequest registerRequest) {
        UserRegisterResponse response = new UserRegisterResponse();

        // 判空验证
        registerRequest.requestCheck();

        // 验证用户名, 邮箱是否重复
        try {
            validUserNameRepeat(registerRequest);
            validEmailRepeat(registerRequest);
        } catch (ValidateException e){
            response.setCode(e.getErrorCode());
            response.setMsg(e.getMessage());
            return response;
        }

        // 1. 向tb_member插入一条记录
        Member member = new Member();
        member.setUsername(registerRequest.getUserName());
        member.setEmail(registerRequest.getEmail());
        // password 加密
        String userPassword = DigestUtils.md5DigestAsHex(registerRequest.getUserPwd().getBytes());
        System.out.println("注册未加密的密码：" + registerRequest.getUserPwd());
        System.out.println("注册加密后的密码：" + userPassword);
        member.setPassword(userPassword);

        member.setUpdated(new Date());
        member.setCreated(new Date());
        member.setIsVerified("N");
        member.setState(1);

        int effectRows = memberMapper.insert(member);
        if (effectRows != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        System.out.println("插入tb_number表成功");


        // 2. 向tb_user_verify插入一条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String key = member.getUsername() + member.getPassword() + UUID.randomUUID().toString();
        // 加密uuid
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsVerify("N");
        userVerify.setIsExpire("N");
        int rows = userVerifyMapper.insert(userVerify);
        if (rows != 1) {
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }
        System.out.println("插入tb_user_verify成功");

        // 3. 发送用户激活邮件
        //TODO 发送用户激活邮件, 消息队列, 消息中间间MQ
        sendEmail(uuid, registerRequest);

        // 打印日志
        log.info("用户注册成功，注册参数request:{},{}", JSON.toJSONString(registerRequest), "xxx");
        // 用户注册成功，注册参数 request: xxx
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    private void validEmailRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("email", registerRequest.getEmail());
        List<Member> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            throw new ValidateException(SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getCode(), SysRetCodeConstants.EMAIL_ALREADY_EXISTS.getMessage());
        }
    }

    private void sendEmail(String uuid, UserRegisterRequest registerRequest) {

        SimpleMailMessage message = new SimpleMailMessage();

        message.setSubject(mailConfig.getSubject());
        message.setFrom(mailConfig.getFrom());
        message.setTo(registerRequest.getEmail());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:8080/user/verify?uid=").append(uuid).append("&username=").append(registerRequest.getUserName());
        // http://localhost:8080/user/verify?uid=xxxx&username=xxx
        message.setText(stringBuilder.toString());

        mailSender.send(message);
    }

    private void validUserNameRepeat(UserRegisterRequest registerRequest) {
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username", registerRequest.getUserName());
        List<Member> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(), SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }

    }
}